var express = require('express');
var router = express.Router();
var MongoClient = require('mongodb').MongoClient;
/* GET users listing. */

var DB_CONN_STR="mongodb://127.0.0.1:2717/user";


router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

router.get('/loginAction',function(req,res,next){
	var selectData=function(db,callback){
		var conn=db.collection('user_name');
		var data={email:req.query.email,password:req.query.password};
		conn.find(data).toArray(function(err,results){
			callback(results);
		});
	}
	MongoClient.connect(DB_CONN_STR,function(err,db){
		if(err){
			console.log("连接错误");
		}else{
			selectData(db,function(results){
				if(results.length>0){
					req.session.email=results[0].email;
					req.redirect('');
				}else{
					res.send('用户名或密码错误');
				}
			})
		}
	});
});


router.post('/registerAction',function(req,res,next){
	var insertData=function(db,callback){
		var conn=db.collection('user_name');
		var data={email:req.query.email,password:req.query.password};
		conn.insert(data,function(err,results){
			if(err){
				console.log(err);
				return;
			}else{
				callback(results);
			}
		})
	}
	MongoClient.connect(DB_CONN_STR,function(err,db){
		if(err){
			console.log("连接错误");
		}else{
			insertData(db,function(results){
				res.send('注册成功');
			})
		}
	});
});




module.exports = router;
